import Const from "./const"
import Vue from "vue"
import VueResource from "vue-resource"
import Core from "../core"

function Api() {
  Vue.use(VueResource);

  const apiList = {
    Admin: {
      login: ['admin/login', 'username', 'password'],
    }
  };


  function generateApi() {
    let API = this;
    for (let moduleKey in apiList) {

      let moduleApiList = apiList[moduleKey];
      API[moduleKey] = {};

      for (let functionName in moduleApiList) {
        let config = moduleApiList[functionName];

        API[moduleKey][functionName] = ((config) => {
          return (...args) => {
            return post(config, ...args)
          };
        })(config);
      }
    }
  }

  function getUrl(api, data) {
    let token = Core.Data.getToken() || "";
    let url = `${Const.NET.END_POINT}/${api}`;
    let params = {
      token: token
    };

    data = Object.assign(params, data);
    url = url + '?' + transformObjectToUrlencodedData(data);
    return url;
  }

  this.getUrl = getUrl;

  generateApi.call(this);

  function post(api, ...args) {
    let token = Core.Data.getToken() || "";
    let url = window.location.href;

    url = `${url}/${api[0]}`;
    let body = '';

    let params = {
      token: token
    };

    let requestArr = {};
    for (let i = 1; i < api.length; i++) {
      let param = args[i - 1];
      param = param === undefined ? "" : param;
      // body += `&${api[i]}=${param}`
      requestArr[api[i]] = param;
    }

    body = Object.assign(params, requestArr);

    console.log(url + "?" + transformObjectToUrlencodedData(body));

    let headers = {
      'Content-Type': 'application/x-www-form-urlencoded'
    };
    return new Promise((resolve, reject) => {
      Vue.http.post(url, transformObjectToUrlencodedData(body), {headers: headers}).then(
        response => {
          let body = response.body;
          if (response.data.hasOwnProperty('code') && response.data.code === Const.ERROR.ERROR_TOKEN_INVALID) {
            Core.Data.clearAuthData();
            return;
          }
          if (body.hasOwnProperty('code') && body.code === 0) {
            if (body.hasOwnProperty('error')) {
              console.error(body.error);
              handleError(body.error);
              return reject(body.error);
            } else {
              return resolve(body.data)
            }
          }

          handleError(body.message);
          return reject(body);
        },
        error => {
          handleError(error.message);
          reject(error);
        }
      );
    })
  }

  function handleError(message) {
    //Message({ type: "error", message: message });
  }

  function transformObjectToUrlencodedData(obj) {
    let p = [];
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        p.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
      }
    }
    return p.join('&');
  }

  return this;

}

export default new Api();
